package com.zc.Interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义拦截器
 */

@Slf4j
public class UserInfoInterceptor implements HandlerInterceptor {
    /**
     * 拦截请求，访问controller之前
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        log.error("拦截请求，访问controller之前");

        String userId = request.getHeader("userId");
        String token = request.getHeader("token");

        /*if(StringUtils.isEmpty(userId) || StringUtils.isEmpty(token)){
            ZcException.display(ErrorEnum.E_10002);
            return false;
        }*/

        //假设真实的用户信息id是1001，用户token是123456
        /*if(!userId.equals("1001") || !token.equals("123456")){
            ZcException.display(ErrorEnum.E_10003);
            return false;
        }*/

        /**
         * false:请求被拦截
         * true:请求放行，可以继续访问后边的controller
         */

        return true;
    }

    /**
     * 请求访问controller之后，渲染视图之前
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.error("请求访问controller之后，渲染视图之前");
    }

    /**
     * 请求访问controller之后，渲染视图之后
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.error("请求访问controller之后，渲染视图之后");

    }
}
